package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.cache.repository.IDistrictCacheRepository;
import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.basic.pojo.entity.District;
import cn.tedu.tmall.basic.service.IDistrictService;
import cn.tedu.tmall.common.pojo.po.DistrictSimplePO;
import cn.tedu.tmall.common.pojo.vo.PageData;
import cn.tedu.tmall.common.util.PageInfoToPageDataConverter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DistricService implements IDistrictService {
    @Autowired
    private IDistrictRepository districtRepository;

    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    @Override
    public List<DistrictSimplePO> listByParent(Long parentId) {
        List<DistrictSimplePO> cacheList = districtCacheRepository.listByParent(parentId);
        if (cacheList.size()==0){
            List<DistrictSimplePO> dblist=districtRepository.listByParent(parentId);
            return dblist;
        }
        return cacheList;
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();
        Long parentId = 0L;
        List<DistrictSimplePO> districtList = districtRepository.listByParent(parentId);
        districtCacheRepository.saveListByParent(parentId, districtList);
        callRecursion(districtList);
    }

    @Override
    public void rebuildCacheList() {
        districtCacheRepository.delete();
        Integer pageNum = 1;
        Integer maxPage;
        do {
            PageData<DistrictSimplePO> list = districtRepository.list(pageNum, 60);
            for (DistrictSimplePO districtSimplePO : list.getList()) {
                districtCacheRepository.save(districtSimplePO.getCode(),districtSimplePO);
            }
            maxPage = list.getMaxPage();
            pageNum++;
        }while (pageNum<=maxPage);

    }

    private void callRecursion(List<DistrictSimplePO> districtList) {
        for (DistrictSimplePO district : districtList) {
            Long id = district.getId();
            List<DistrictSimplePO> subList = districtRepository.listByParent(id);
            if (subList.size() > 0) {
                districtCacheRepository.saveListByParent(id, subList);
                callRecursion(subList);
            }
        }

    }
}
